package com.agp.test.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xie
 */
public class Customer implements Runnable{

    private Lock lock = new ReentrantLock();
    private Boolean flag = false;
    private Condition condition = lock.newCondition();
    private int number = 1;




    public Customer(Lock lock, Boolean flag) {
        this.lock = lock;
        this.flag = flag;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        lock.lock();
        try {
            while (flag == false) {
                //等待通知进行消费
                condition.await();
                System.out.println("接收到消费通知,开始消费");
            }

            System.out.println(Thread.currentThread().getName() + "-----消费-----");
            number--;
            System.out.println("number: " + number);
            TimeUnit.MILLISECONDS.sleep(1000);

            flag = false;
            //通知进行生产
            condition.signalAll();

        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
